package com.zoe.onelink.logging.trace.redis;

import com.zoe.onelink.common.constant.OnelinkMetricsConstant;
import io.lettuce.core.metrics.CommandLatencyCollectorOptions;
import io.lettuce.core.metrics.DefaultCommandLatencyCollector;
import io.lettuce.core.metrics.DefaultCommandLatencyCollectorOptions;
import io.lettuce.core.protocol.ProtocolKeyword;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2023</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2023-01-03
 */
@Slf4j
public class OnelinkCommandLatencyCollector extends DefaultCommandLatencyCollector {

    public OnelinkCommandLatencyCollector() {
        this(DefaultCommandLatencyCollectorOptions.create());
    }

    public OnelinkCommandLatencyCollector(CommandLatencyCollectorOptions options) {
        super(options);
    }

    @Override
    public void recordCommandLatency(SocketAddress local, SocketAddress remote, ProtocolKeyword commandType, long firstResponseLatency, long completionLatency) {
        if (!this.isEnabled()) {
            return;
        }
        Tags tags = Tags.of("commandType", commandType.name());
        Metrics.counter(OnelinkMetricsConstant.Redis.REQUEST_COUNT, tags).increment();
        // 1000毫秒以上的请求
        if (completionLatency > 1_000_000_000) {
            log.warn("[REDIS_SLOW_LOG] {} -> {} | {} | firstResponseLatency:{}ms | completionLatency:{}ms",
                    local, remote, commandType.name(), firstResponseLatency / 1_000_000, completionLatency / 1_000_000);
        }
        super.recordCommandLatency(local, remote, commandType, firstResponseLatency, completionLatency);
    }
}
